const app = getApp()
const {
  upTime
} = require('/util/public')
const {
  activeProMoney
} = require("/util/handler_page/activeProduct")
Page({
  data: {},
  onLoad(query) {
    app._init_(this)
    this.setData({
      query
    })
    this.get_msg()
  },

  // 获取信息
  get_msg() {
    app.order.detail(this.data.query.param)
      .then(async res => {
        console.log("priceprice", res.data)
        res.data.params = JSON.parse(res.data.params);
        res.data.paymentParams = JSON.parse(res.data.paymentParams);
        res.data.isFirstPrice = true
        // 期数
        res.data.leaseTerm = parseInt(res.data.leaseTerm);
        // 首期租金
        let yu = res.data.params.model.price % res.data.leaseTerm;

        // 有余数
        if (yu > 0) {
          // 有余数
          res.data.isYu = true
          // 剩余租期
          res.data.lastTerm = res.data.leaseTerm - 1
        } else {
          // 无余数
          res.data.isYu = false
          // 剩余租期
          res.data.lastTerm = res.data.leaseTerm
        }
        // 每期价格
        let meiqiPrice = (res.data.params.model.price - yu) / res.data.leaseTerm
        // 尾期价格
        res.data.lastRent = ((meiqiPrice * 1 + yu * 1) / 100).toFixed(2)
        // 首期价格
        res.data.firstRent = (meiqiPrice / 100).toFixed(2)
        // 是否有自定义首期
        if (res.data.firstPrice) {
          res.data.isFirstPrice = false
          // 首期价格
          res.data.firstRent = (res.data.firstPrice / 100).toFixed(2)
          // 尾期余数
          let yuPrice = (res.data.params.model.price - res.data.firstPrice) % (res.data.leaseTerm - 1)
          console.log("yu", yuPrice);
          // 有余数
          if (yuPrice > 0) {
            // 有余数
            res.data.isYu = true
            // 剩余租期
            res.data.lastTerm = res.data.leaseTerm - 1
          } else {
            // 无余数
            res.data.isYu = false
            // 剩余租期
            res.data.lastTerm = res.data.leaseTerm
          }
          // 每期价格
          let meiqiPrice = (res.data.params.model.price - res.data.firstPrice - yuPrice) / res.data.lastTerm
          res.data.meiqiPrice = (meiqiPrice / 100).toFixed(2)
          // 尾期价格
          res.data.lastRent = ((meiqiPrice * 1 + yuPrice * 1) / 100).toFixed(2)
        }
        // 总租金
        res.data.allRent = res.data.params.model.price / 100; //app.fenToYuan(res.data.params.allRent);
        // 总押金
        res.data.allDeposit = res.data.params.deposit / 100; //app.fenToYuan(res.data.params.allDeposit);
        // 完结价
        res.data.buyoutPrice = res.data.params.buyOutPrice

        console.log("data->{}", res.data)
        res.data = await activeProMoney(res.data)

        res.data.date = upTime("%Y-%M-%D %h:%m:%s", res.data.createtime);
        res.data.createtime = upTime("%Y-%M-%D", res.data.createtime);
        res.data.starttime = upTime("%Y-%M-%D", res.data.starttime) || '';
        res.data.endtime = upTime("%Y-%M-%D", res.data.endtime) || '';


        let puyAmount = 0
        res.data.productOrderRecordVoList.forEach(item => {
          item.createtime = item.createtime ? upTime("%Y-%M-%D", item.createtime) : '';
          item.expiretime = item.expiretime ? upTime("%Y-%M-%D", item.expiretime) : '';
          item.duetime = item.duetime ? upTime("%Y-%M-%D", item.duetime) : '';
          if (item.payment == 1) {
            puyAmount += item.price / 100
          }
        })
        res.data.puyAmount = puyAmount
        let item = res.data
        console.log(item)
        // this.setData(res.data);
        this.setData({
          item: item
        });
      })
  },

  //   联系商家
  makePhoneCall(e) {
    // console.log(e.target.dataset.phone)
    let phone = e.target.dataset.phone;
    my.makePhoneCall({
      number: phone
    });
  },

  // 签署协议
  signClick() {
    app.order.sign(this.data.item.id)
      .then(res => {
        console.log("================>>签署协议", res)
        this.navigateToMiniProgram(res.data)

      })
  },
  // 跳转签署小程序
  navigateToMiniProgram(str) {
    // str = "alipays://platformapi/startapp?appId=2021001152620480&page=pages/signH5/index&query=signUrl%3Dhttps%253A%252F%252Ftsign.cloud.alipay.com%252Fweb%252FhandMultifileSign%253Ftimestamp%253D1646124493022%2526flowId%253D5fab96b4da5246fdb963b8c0a83c441f%2526accountId%253DDAWRSKNY1%2526sign%253Dcb0fa54e86b4c98b29056fcd81903d43b4caae0664f2bb76bf1d111f2c7af313"
    let signUrl = this.getSignUrl(str)
    my.navigateToMiniProgram({
      appId: '2021001152620480',
      path: `pages/signH5/index?signUrl=${signUrl}`,
      success: (res) => {
        console.log(JSON.stringify(res))
      },
      fail: (res) => {
        console.log(JSON.stringify(res))
      }
    });
  },
  // 格式化链接
  getSignUrl(aliSchema) {
    if (!aliSchema) {
      return ''
    }
    const querys = aliSchema.split('?')[1].split('&');
    const signUrlKeyValue = querys.find((item) => item.includes('query=')).replace('query=', '');
    const encodedSignUrl = decodeURIComponent(signUrlKeyValue).replace('signUrl=', '');
    return encodedSignUrl
  },
  // 关闭订单
  onCancel(e) {
    // console.log(e.target.dataset.item)
    let id = e.target.dataset.item.id;
    let status = e.target.dataset.item.status;
    my.prompt({
      title: '申请取消',
      message: '请输入取消原因，否则无法为你取消',
      placeholder: '请输入取消原因',
      okButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        console.log(result)
        if (!result.ok) {
          return
        }
        if (result.inputValue) {
          if (status == 1) {
            app.order.canOrder(id, {
                cont: result.inputValue
              })
              .then((res) => {
                my.alert({
                  title: "取消成功",
                  success: () => {
                    this.resetOrder()
                  }
                });
              })
          } else if (status == 2) {
            app.order.canOrder(id, {
                cont: result.inputValue
              })
              .then((res) => {
                console.log(res)
                my.alert({
                  title: "申请成功",
                  success: () => {
                    this.resetOrder()
                  }
                });

              })
          }
        } else {
          my.showToast({
            type: 'exception',
            content: '请输入取消原因',
          });
        }
      },
    });
  },
  // 撤销申请
  noCancel(e) {
    let cancelRequests = e.target.dataset.item.productOrderCancelRequests
    let id = cancelRequests[cancelRequests.length - 1].id
    my.confirm({
      title: '温馨提示',
      content: '是否撤回订单取消申请',
      confirmButtonText: '立即撤回',
      cancelButtonText: '暂不撤回',
      success: (result) => {
        if (result.confirm) {
          app.order.canOrder(id)
            .then(red => {
              if (res.code == 200) {
                my.alert({
                  title: "撤回成功",
                  success: () => {
                    this.resetOrder()
                  }

                });
              }
            })
        }
      },
    });
  },

  // 冻结
  onBuy(e) {
    let that = this
    const data = e.target.dataset.data;
    app.order.freeze(data.id)
      .then(pay => {
        my.tradePay({
          orderStr: pay.data, // 完整的支付参数拼接成的字符串，从服务端获取
          success: (res) => {
            console.log(res)
            if (res.resultCode == 9000) {
              my.alert({
                content: "支付成功",
              });
              this.resetOrder()
            }
          },
          fail: (res) => {
            my.alert({
              content: res.memo,
            });
          }
        });
      })
  },
  // 支付
  onReplenish(e) {
    let that = this
    let oid = e.target.dataset.data.productOrderRecordVoList[0].oid
    let id = e.target.dataset.data.productOrderRecordVoList[0].id
    app.order.alipay(oid, id)
      .then(res => {
        my.tradePay({
          tradeNO: res.data,
          success: function (res) {
            // console.log(res)
            if (res.resultCode == 9000) {
              my.alert({
                content: "支付成功",
              });
              this.resetOrder()
            } else {
              my.alert({
                content: res.memo,
              });
            }
          },

        });
      })
  },
  // 确认收货
  ConfirmReceipt(e) {
    let id = e.target.dataset.id
    app.order.receiving(id)
      .then(res => {
        if (res.code == 200) {
          my.alert({
            content: "提交成功",
            success: () => {
              this.resetOrder()
            }
          })
        } else {
          my.alert({
            content: res.msg
          })
        }
      })
  },


  // 买断
  buyoutBtn(options) {
    my.confirm({
      title: '温馨提示',
      content: '确定要买断吗？买断后需支付剩余尾款。',
      confirmButtonText: '马上买断',
      cancelButtonText: '暂不需要',
      success: (result) => {
        if (result.confirm) {
          console.log("11111111111111", options.target.dataset.param.id)
          const oid = options.target.dataset.param.id;
          app.order.buyout(oid)
            .then(res => {
              console.log("返回消息", res)

              if (!res.data) {
                my.showToast({
                  content: '请联系客服买断！',
                });
                return;
              }
              app.alipay(res.data).then(pay => {
                if (pay.resultCode == 9000) {
                  my.showToast({
                    content: '支付成功',
                  });
                }
              })
            })
        }

      }
    })
  },

  // 跳转
  navigateTo(e) {
    app.navigateTo(e)
  }
});